const express = require("express");
const multer = require("multer");
const upload = multer({ dest:"./upload" });
const cookieParser = require("cookie-parser");
// const session = require("express-session");
const jwt = require("jsonwebtoken");

// 引入各个路由模块
const loginRouter = require("./routers/login");

const userRouter = require("./routers/user/index");
const userAddRouter = require("./routers/user/add");
const userSetRouter = require("./routers/user/set");
const userSetPasswordRouter = require("./routers/user/setPassword");
const userSetAvatarRouter = require("./routers/user/setAvatar");
const userDelRouter = require("./routers/user/del");
const userExportRouter = require("./routers/user/export");
const userImportRouter = require("./routers/user/import");

const meetRoomRouter = require("./routers/meetRoom/index");
const meetRoomAddRouter = require("./routers/meetRoom/add");
// const meetRoomSetRouter = require("./routers/meetRoom/set");

const meetingRouter = require("./routers/meeting/");
const meetingAddRouter = require("./routers/meeting/add");


const app = express();

// 注册中间件
app.use( express.static("./upload") );  // 
app.use( express.static("./www") );     // 
app.use( express.urlencoded() );
app.use( cookieParser() );
app.use( upload.any() );
// app.use( session({
//     secret: 'helloworld',   // 加密信息，可以随便写
//     resave: false,      // 强制保存session，默认为true，建议设置为false
//     saveUninitialized: true,    // 强制将未初始化的session存储，默认为true，建议为true
//     cookie: { maxAge: 1000 * 60 * 30 }    // 过期时间，毫秒数
// }) )

// 注册路由
// 登录
app.get("/login", loginRouter);

app.all("*", (req,res,next)=>{
    // 登录验证-cookie
    // if(req.cookies.isLogin !== "ok"){

    // 登录验证-session
    // if(req.session.isLogin !== "ok"){
    
    // 登录验证-token
    // 先从前端接收到token字符
    const tokenStr = req.method.toUpperCase() === "GET" ? req.query.token : req.body.token;
    // 使用jwt模块，解析接收到的token字符
    jwt.verify(tokenStr, "千锋H5", (err, data)=>{
        if(err){
            // 解析失败
            res.send({
                code:2,
                msg:"登录失效或未登录"
            })
        }else{
            // 解析成功
            // console.log(data);
            next();
        }
    });

})

// 用户管理
app.get("/user", userRouter);
app.post("/user/add", userAddRouter);
app.post("/user/set", userSetRouter);
app.post("/user/setpassword", userSetPasswordRouter);
app.post("/user/del", userDelRouter);
app.post("/user/setavatar", userSetAvatarRouter);
app.get("/user/export", userExportRouter);
app.post("/user/import", userImportRouter);

// 会议室管理
app.get("/meet", meetRoomRouter);
app.post("/meet/add", meetRoomAddRouter);
// app.post("/meet/set", meetSetRouter);

// 会议管理
app.get("/meeting", meetingRouter);
app.post("/meeting/add", meetingAddRouter);

app.listen(3000,()=>{
    console.log("服务器开启成功，BaseURL为：http://localhost:3000")
});





// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc0xvZ2luIjoib2siLCJpYXQiOjE2NzkwMjI0ODIsImV4cCI6MTY3OTAyNDI4Mn0.bN-i8yrooolvPmiuWWGuu8Z7nPjuQTK5Xdo8MMjyBT4